package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Autowired
    private ISeckillVoucherService seckillVoucherService;
    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setResultType(Long.class);
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
    }


    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();//单线程
    @PostConstruct  //当前类初始化完毕后执行
    private void init(){
        //开启独立线程 处理订单写入数据库
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

        private class VoucherOrderHandler implements Runnable{
        String queueName = "stream.orders";
        @Override
        public void run() {
            while (true){
                try {
                    //1.获取redis 消息队列 订单信息 xreadgroup group g1 c1 count 1 block 2000 STREAMS stream.orders >   >表示从上一次消费的消息继续消费
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    //2.判断消息是否获取成功
                    if (list == null || list.isEmpty()){
                        //3.消息为空，获取失败，继续循环获取消息
                        continue;
                    }
                    //4.消息不为空，获取成功，解析消息 ，下单写入数据库
                    //因为这里count 1 ，，每次只读了消息队列的一个消息，因此订单就是队列的第一个元素
                    MapRecord<String, Object, Object> entries = list.get(0); //这里string是消息id，后面是订单信息的键值对
                    Map<Object, Object> value = entries.getValue(); //拿到订单信息的键值对
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    handleVoucherOrder(voucherOrder);
                    //5.ACK确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",entries.getId());

                } catch (Exception e) {
                    log.error("处理订单异常："+e);
                    //抛出异常，表示消息没有被正确处理，不会被ack确认，进入redis消息队列的pending-list
                    handlePendingList();
                }
            }
        }
        private void handlePendingList(){
            while (true){
                try {
                    //1.获取redis pending-list队列 订单信息 xreadgroup group g1 c1 count 1  STREAMS stream.orders 0   0表示从pending-list消费，读取分配给消费者 c1 且尚未被确认 (ACKed) 的消息 (PEL - Pending Entries List)
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );
                    //2.判断消息是否获取成功
                    if (list == null || list.isEmpty()){
                        //3.消息为空，获取失败，表示pending-list没有消息了，直接跳出循环
                        break;
                    }
                    //4.消息不为空，获取成功，解析消息 ，下单写入数据库
                    //因为这里count 1 ，，每次只读了消息队列的一个消息，因此订单就是队列的第一个元素
                    MapRecord<String, Object, Object> entries = list.get(0); //这里string是消息id，后面是订单信息的键值对
                    Map<Object, Object> value = entries.getValue(); //拿到订单信息的键值对
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    handleVoucherOrder(voucherOrder);
                    //5.ACK确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",entries.getId());

                } catch (Exception e) {
                    log.error("处理pending-list订单异常："+e);
                    try {
                        Thread.sleep(20);//防止循环太频繁
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }

                }
            }
        }
    }
//    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024*1024);
//    private class VoucherOrderHandler implements Runnable{
//
//        @Override
//        public void run() {
//            while (true){
//                try {
//                    //1.获取阻塞队列 订单信息
//                    VoucherOrder voucherOrder = orderTasks.take();
//                    //2.创建订单（写入数据库）
//                    handleVoucherOrder(voucherOrder);
//                } catch (Exception e) {
//                    log.error("处理订单异常："+e);
//                }
//            }
//        }
//    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        //1.获取用户，这里不在从ThreadLocal中获取，因为是新的线程,而是从订单中获取
        Long userId = voucherOrder.getUserId();
        //2.创建锁对象
//        SimpleRedisLock lock = new SimpleRedisLock(stringRedisTemplate, "seckillOrder:" + userId);
        RLock lock = redissonClient.getLock("lock:seckillOrder:" + userId);
        //3.获取锁
        boolean isLock = lock.tryLock();
//        boolean isLock = lock.tryLock(1200);
        if (!isLock){
            //获取锁失败，这里不在返回错误信息，因为是新线程异步处理订单任务，不需再给前端反馈
            log.error("不允许重复下单");
            return;
        }
        try {
            //执行数据库操作 创建订单
            proxy.createVoucherOrder(voucherOrder);
        } finally {
            //释放锁
            lock.unlock();
        }
    }
    private IVoucherOrderService proxy;
    public Result seckillVoucher(Long voucherId) throws InterruptedException {   //CAS法(Compare and Set) 防止超卖 乐观锁
        //使用lua脚本优化秒杀流程 减少访问数据库的次数
        Long userId = UserHolder.getUser().getId();
        long orderId = redisIdWorker.nextId("order");
        //1.执行lua脚本
        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT,
                Collections.emptyList(), voucherId.toString(), userId.toString(),String.valueOf(orderId));

        //2.根据返回值 判断是否为0
        int i = result.intValue();
        if (i != 0){
            //3.返回值不为0，返回错误信息
            return Result.fail(i==1 ?"库存不足！":"请勿重复下单！");
        }
        //4.返回值为0,有资格购买，把下单信息保存到阻塞队列中，开启一个新线程 把访问数据库的任务交给异步线程，而主线程则返回订单id
        proxy = (IVoucherOrderService) AopContext.currentProxy();//获取代理对象
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setUserId(userId);
        voucherOrder.setId(orderId);
        // 生产Kafka消息
        String topic = "seckill_order";
        String jsonStr = JSONUtil.toJsonStr(voucherOrder);
        ListenableFuture<SendResult<String, Object>> resultListenableFuture = kafkaTemplate.send(topic, jsonStr);

        resultListenableFuture.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable ex) {
                log.error("kafka sendMessage error, ex = {}, topic = {}, data = {}", ex, topic, voucherOrder);
            }

            @Override
            public void onSuccess(SendResult<String, Object> stringObjectSendResult) {
                log.info("kafka sendMessage success topic = {}, data = {}", topic, voucherOrder);

            }
        });
        log.info("kafka sendMessage end");


        return Result.ok(orderId);



    }
//    public Result seckillVoucher(Long voucherId) throws InterruptedException {   //CAS法(Compare and Set) 防止超卖 乐观锁
//        //使用lua脚本优化秒杀流程 减少访问数据库的次数
//        Long userId = UserHolder.getUser().getId();
//        //1.执行lua脚本
//        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT,
//                Collections.emptyList(), voucherId.toString(), userId.toString());
//
//        //2.根据返回值 判断是否为0
//        int i = result.intValue();
//        if (i != 0){
//            //3.返回值不为0，返回错误信息
//            return Result.fail(i==1 ?"库存不足！":"请勿重复下单！");
//        }
//        //4.返回值为0,有资格购买，把下单信息保存到阻塞队列中，开启一个新线程 把访问数据库的任务交给异步线程，而主线程则返回订单id
//        proxy = (IVoucherOrderService) AopContext.currentProxy();//获取代理对象
//        //创建订单
//        VoucherOrder voucherOrder = new VoucherOrder();
//        long orderId = redisIdWorker.nextId("order");
//        voucherOrder.setVoucherId(voucherId).setUserId(userId).setId(orderId);
//
//        orderTasks.put(voucherOrder); //将订单信息放入阻塞队列
//        return Result.ok(orderId);
//
//        //创建锁对象
////        SimpleRedisLock lock = new SimpleRedisLock(stringRedisTemplate, "seckillOrder:" + userId);
////        RLock lock = redissonClient.getLock("lock:seckillOrder:" + userId);
////        //获取锁
////        boolean isLock = lock.tryLock();
//////        boolean isLock = lock.tryLock(1200);
////        if (!isLock){
////            //获取锁失败，返回错误信息
////            return Result.fail("请勿重复下单");
////        }
////        try {
////            //获取代理对象（事务）
////            IVoucherOrderService proxy =(IVoucherOrderService) AopContext.currentProxy();
////            return proxy.createVoucherOrder(voucherId);
////        } finally {
////            //释放锁
////            lock.unlock();
////        }
//
//    }
//    @Override
//    public Result seckillVoucher(Long voucherId) {   //CAS法(Compare and Set) 防止超卖 乐观锁
//        //1.查询优惠券
//        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
//        //2.判断秒杀是否开始
//        LocalDateTime beginTime = voucher.getBeginTime();
//        LocalDateTime endTime = voucher.getEndTime();
//        if (beginTime.isAfter(LocalDateTime.now())){
//            return Result.fail("秒杀尚未开始！！");
//        }
//        //3.判断秒杀是否结束
//        if (endTime.isBefore(LocalDateTime.now())){
//            return Result.fail("秒杀已经结束！！");
//        }
//        //4.判断库存是否充足
//        Integer stock = voucher.getStock();
//        if (stock <= 0){
//            return Result.fail("库存不足！！");
//        }
//        //一人一单
//        Long userId = UserHolder.getUser().getId();
////        synchronized (userId.toString().intern()){
////            //获取代理对象（事务）
////            IVoucherOrderService proxy =(IVoucherOrderService) AopContext.currentProxy();
////            return proxy.createVoucherOrder(voucherId);
////        }
//        //创建锁对象
////        SimpleRedisLock lock = new SimpleRedisLock(stringRedisTemplate, "seckillOrder:" + userId);
//        RLock lock = redissonClient.getLock("lock:seckillOrder:" + userId);
//        //获取锁
//        boolean isLock = lock.tryLock();
////        boolean isLock = lock.tryLock(1200);
//        if (!isLock){
//            //获取锁失败，返回错误信息
//            return Result.fail("请勿重复下单");
//        }
//        try {
//            //获取代理对象（事务）
//            IVoucherOrderService proxy =(IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
//        } finally {
//            //释放锁
//            lock.unlock();
//        }
//
//    }
    @Transactional
    @Override
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        //一人一单
        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();
        Integer count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        if (count>0){
            log.error("用户已经购买过该优惠券了！");
            return;
        }
        //5.扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock -1")
                .eq("voucher_id", voucherId)
                .gt("stock",0)               //where id = ? and stock > 0
//                .eq("stock", stock)
                .update();

        if (!success){
            log.error("库存不足！");
            return;
        }
        //6.创建订单 订单id（用之前定义的工具生成）   用户id  优惠券的id
//        VoucherOrder voucherOrder = new VoucherOrder();
//        voucherOrder.setVoucherId(voucherId);
//
//        voucherOrder.setUserId(userId);
//        long orderId = redisIdWorker.nextId("order");
//        voucherOrder.setId(orderId);

        save(voucherOrder);
        //7.返回订单号
//        return Result.ok(orderId);
    }

    @KafkaListener(topics = "seckill_order")
    @Transactional
    public void processMessage(ConsumerRecord<String, Object> record, Acknowledgment ack) {
        try {
            // 获取消息内的数据
            String data = (String) record.value();
            VoucherOrder order = JSONUtil.toBean(data, VoucherOrder.class);

            // 1. 生成订单... 操作数据库
            //一人一单
            Long userId = order.getUserId();
            Long voucherId = order.getVoucherId();
            Integer count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
            if (count>0){
                log.error("用户已经购买过该优惠券了！");
                return;
            }

            // 2. 扣减库存... 操作数据库
            boolean success = seckillVoucherService.update()
                    .setSql("stock = stock -1")
                    .eq("voucher_id", voucherId)
                    .gt("stock",0)               //where id = ? and stock > 0
                    .update();

            if (!success){
                log.error("库存不足！");
                return;
            }

            save(order);
            ack.acknowledge(); // 仅业务成功时提交
            log.info("秒杀订单-消息消费成功：topic={},offset={},value={}",record.topic(),record.offset(),record.value());
        } catch (Exception e) {
            log.error("消费异常: topic={}, offset={}, 原因={}",
                    record.topic(), record.offset(), e.getMessage());
            // 不提交！等待重试或进入死信队列
        }
    }
}
